<template>
    <div class="productAddWrap">
        <div class="title">新增产品</div>
        <el-form ref="form" :model="form" label-width="109px">
          <el-form-item label="产品品类" :rules="[{ required: true, message: '不能为空'}]">
            <el-cascader
              :options="productTypeList"
              v-model="form.sub_model_id"
              >
            </el-cascader>
          </el-form-item>
          <el-form-item label="产品模板" :rules="[{ required: true, message: '不能为空'}]">
            <el-select v-model="form.useTemplate">
              <el-option label="不使用" value="noneUse"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择接入方式" :rules="[{ required: true, message: '不能为空'}]">
            <el-select v-model="form.access_id" @change="accessTypeChange">
              <el-option 
                v-for="item in accesTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select> 
          </el-form-item>
          <el-form-item label=""  v-if="sub_model.length">
            <el-radio-group v-model="form.access_sub_id">
              <el-radio-button label="设备直连平台" v-if="sub_model[0]"></el-radio-button>
              <el-radio-button label="设备经应用网关直连平台" v-if="sub_model[1]"></el-radio-button>
              <el-radio-button label="应用网关" v-if="sub_model[2]"></el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="设备识别类型" :rules="[{ required: true, message: '不能为空'}]">
            <el-select v-model="form.dev_distinguish_type">
              <el-option 
                v-for="item in identificationTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配网方式" :rules="[{ required: true, message: '不能为空'}]">
            <el-select v-model="form.network_type" @change="networkChange">
              <el-option 
                v-for="item in networkList"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <transition name="el-zoom-in-center">
          <el-form-item label="模组" v-show="show1" :rules="[{ required: true, message: '不能为空'}]">
            <el-select v-model="form2.module_id">
              <el-option 
                v-for="item in moduleList"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          </transition>
          <transition name="el-zoom-in-center" :rules="[{ required: true, message: '不能为空'}]">
          <el-form-item label="热点描述" v-show="show2" :rules="[{ required: true, message: '不能为空'}]">
            <el-input type="textarea" v-model="form2.ap_remarks"></el-input>
          </el-form-item>
          </transition>
          <transition name="el-zoom-in-center">
          <el-form-item label="步骤图片" v-show="show1" :rules="[{ required: true, message: '不能为空'}]">
            <img src="@/static/img/default.png" v-if="!form.logo" class="logoImg" id="logoImg2" alt="">
            <div class="input-group"><div class="input-group-addon"><label style="position:relative;"><img src="@/static/img/image.jpg" title="send images" style="cursor:pointer;"><input id="sendImage2" type="file" value="images" style="display:none;"  onchange="window.preview2()"></label></div></div>
          </el-form-item>
          </transition>
          <transition name="el-zoom-in-center">
          <el-form-item label="步骤图说明" v-show="show1" :rules="[{ required: true, message: '不能为空'}]">
            <el-input type="textarea" v-model="form2.step_remarks"></el-input>
          </el-form-item>
          </transition>
          <div class="mywidth">
            <el-form-item label="产品名称" :rules="[{ required: true, message: '不能为空'}]">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="产品型号" :rules="[{ required: true, message: '不能为空'}]">
                <el-input v-model="form.model"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="品牌" :rules="[{ required: true, message: '不能为空'}]">
            <el-select v-model="form.brand_id">
              <el-option 
                v-for="item in brandList"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <span class="addBrand" @click="addBrand">新增品牌+</span>
          </el-form-item>
          <el-form-item label="产品图片(可选)">
            <img src="@/static/img/default.png" v-if="!form.logo" class="logoImg" id="logoImg1" alt="">
            <div class="input-group"><div class="input-group-addon"><label style="position:relative;"><img src="@/static/img/image.jpg" title="send images" style="cursor:pointer;"><input id="sendImage" type="file" value="images" style="display:none;"  onchange="window.preview()"></label></div></div>
          </el-form-item>
          <div class="onSubmit">
            <el-form-item>
              <el-button type="primary" @click="addProduct"><i class="el-icon-upload"></i> 立即创建</el-button>
            </el-form-item>
          </div>
        </el-form>
        <router-link  to="/open/product"><button class="new"><i class="el-icon-back"></i>返回</button></router-link>
    </div>
</template>

<script>
  import $ from 'jquery'
  import _ from 'underscore'
  export default {
     mounted(){
            window.preview=()=>{
                var img = new Image();
                var file=$('#sendImage')[0].files[0]
                var reader=new FileReader()
                reader.onloadend=(e)=>{
                    var data = e.target.result;
                    img.src=data
                }
                reader.readAsDataURL(file)
                img.onload = ()=> {
                    var w = Math.min(400, img.width);
                    var h = img.height * (w / img.width);
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');

                    // 设置 canvas 的宽度和高度
                    canvas.width = w;
                    canvas.height = h;

                    // 把图片绘制到 canvas 中
                    ctx.drawImage(img, 0, 0, w, h);
                    // 取出 base64 格式数据
                    this.img = canvas.toDataURL(file.type);
                    $('#logoImg1').attr('src',this.img)
                }
            } 
            window.preview2=()=>{
                var img = new Image();
                var file=$('#sendImage2')[0].files[0]
                var reader=new FileReader()
                reader.onloadend=(e)=>{
                    var data = e.target.result;
                    img.src=data
                }
                reader.readAsDataURL(file)
                img.onload = ()=> {
                    var w = Math.min(400, img.width);
                    var h = img.height * (w / img.width);
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');

                    // 设置 canvas 的宽度和高度
                    canvas.width = w;
                    canvas.height = h;

                    // 把图片绘制到 canvas 中
                    ctx.drawImage(img, 0, 0, w, h);
                    // 取出 base64 格式数据
                    this.form2.bezouimg = canvas.toDataURL(file.type);
                    $('#logoImg2').attr('src',this.form2.bezouimg)
                }
            }
            this.getAddInfo()
        },
        activated(){
           $('.el-button--primary')[0].setAttribute("style","background-color: rgb(58, 19, 90) !important;border-color: rgb(58, 19, 90) !important")
        },
    data() {
      return {
        form: {
          name:'',
          sub_model_id:[],
          useTemplate:'不使用',
          access_id: '终端直连类',
          access_sub_id:'设备直连平台',
          dev_distinguish_type:'MAC',
          network_type:'其它',
          brand_id:'',
          model:'',
        },
        form2:{
          module_id:'不选择',
          ap_remarks:'',
          step_remarks:'',
          bezouimg:'',
        },
        img:'',
        productTypeList:[//产品类型
        ],
        accesTypeList:[//接入类型
        ],
        sub_model:[true,true,true],//接入子类型
        networkList:[//配网方式
        ],
        identificationTypeList:[//设备识别类型
        ],
        brandList:[],
        moduleList:[{item:'乐鑫(ESP8266)',value:'乐鑫(ESP8266)'}],
        show1:false,
        show2:false
      }
    },
    methods: {
      networkChange(val){
        switch (val) {
          case '蓝牙':
            this.show1=true
            this.show2=false
          break;
          case 'wifi':
            this.show1=true
            this.show2=false
          break;
          case 'AP':
            this.show1=true
            this.show2=true
          break;
          default:
            this.show1=false
            this.show2=false
          break;
        }
      },
      addProduct() {
          var hasEmpty=false
          var data=JSON.parse(JSON.stringify(this.form))
          var data2=JSON.parse(JSON.stringify(this.form2))
          if(this.show1==true&&this.show2==false){
            _.extendOwn(data,data,data2)
            delete data.ap_remarks
          }else if(this.show1==true&&this.show2==true){
            _.extendOwn(data,data,data2)
          }
          _.each(data,(value,index)=>{
              if($.trim(value)==''){
                  hasEmpty=true
                  return
              }else if(data.sub_model_id.length==0){
                  hasEmpty=true
                  return
              }
              if(data.access_id=='终端直连类'){
                data.access_id=1
              }
              if(data.access_sub_id=='设备直连平台'){
                data.access_sub_id=1
              }   
          })
          if(hasEmpty){
              this.$message.error({message:'信息填写不完整',duration:1000});
              return
          }
          //设备类型
          data.sub_model_id=data.sub_model_id[1]
          //设备图片
          if(this.img){
            data.img=this.img
          }
          if(this.form2.bezouimg){
            //只要最后的名字
            data.step_pic=this.form2.bezouimg
          }
          //用户token
          data.token=localStorage.getItem('token')
          const loading = this.$loading({
            lock: true,
            text: '产品添加中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          this.$http.post(this.$store.getters.serverIp+'add_product',data).then((response)=>{
            if(response.data.success){
              loading.close();
              this.$router.push({path:'/open/product?isNoSend=true'})
              this.$message.success({message:response.data.info,duration:1000});
            }else{
              loading.close();
              this.$message.error({message:response.data.info,duration:1000});
            }
          }).catch(()=>{

          })
      },
      accessTypeChange(val){
        var val={value:val}
        var index=_.findIndex(this.accesTypeList,val)
        var sub_model=this.accesTypeList[index].sub_model
        if(this.accesTypeList[index].label=='终端直连类'){
          this.sub_model[true,true,true]
        }else{
          this.sub_model=[]
        }
        if(sub_model.length){
          _.each(sub_model,(value)=>{
              if(value.model_id==1)
                this.sub_model[0]=true
              else if(value.model_id==2)
                this.sub_model[1]=true
                else if(value.model_id==3)
                  this.sub_model[2]=true
          })
        }
      },
      getAddInfo(){
       this.$http.post(this.$store.getters.serverIp+'get_add_info',{token:localStorage.getItem('token')}).then((response)=>{
          if(response.data.success){
             //产品类型
             var productTypeList=response.data.data.main_type
              productTypeList=_.map(productTypeList,(productType)=>{
               productType.value=productType.id
               productType.label=productType.name
               productType.children=_.map(productType.sub_type,(sub)=>{
                  sub.label=sub.short_name
                  sub.value=sub.device_id
                  return sub
               })
               return productType
              })
              this.productTypeList=productTypeList

           //接入方式
           var accesTypeList=response.data.data.main_model
           accesTypeList=_.map(accesTypeList,(accessType)=>{
              accessType.value=accessType.id
              accessType.label=accessType.model_name
              return accessType
           })
           this.accesTypeList=accesTypeList

           //设备识虽类型
           var identificationTypeList=response.data.data.unique
           _.each(identificationTypeList,(value)=>{
            var obj={}
            obj.value=value
            obj.label=value
            this.identificationTypeList.push(obj)
           })
            //配网方式
            var networkList=response.data.data.network
            _.each(networkList,(value)=>{
            var obj={}
            obj.value=value
            obj.label=value
            this.networkList.push(obj)
           })
            console.log(networkList)
            //品牌列表
            var brandList=response.data.data.brand
            brandList=_.map(brandList,(value)=>{
              value.value=value.brand_id
              value.label=value.name
              return value
            })
            this.brandList=brandList
            this.form.brand_id=brandList[0].value
            //模组信息
            var moduleList=response.data.data.module
            moduleList=_.map(moduleList,(value)=>{
              value.value=value.id
              value.label=value.module_name+'('+value.model+')'
              return value
            })
            this.moduleList=moduleList
            this.form2.module_id=moduleList[0].value
            
          }
        }).catch((response)=>{

        })
      },
      addBrand(){
        this.$alert(`<div class="myAlert"><span>品牌名称：</span><div><input class="mybutton" id="brandName" type="text"/></div></div>
          <div class="myAlert"><span>品牌备注：</span><div><textarea class="mybutton" id="remarks"  placeholder="(可选)"/></textarea></div></div>
                        `, {
                      dangerouslyUseHTMLString: true,
                      callback:this.addBrandServer,
                      title:'添加品牌'
              });
        
      },
      addBrandServer(action){
        if(action=="confirm"){
          var name=$.trim($('#brandName').val())
          var remarks=$('#remarks').val()
          var data={name:name,token:localStorage.getItem('token'),remarks:remarks}
          if(!name){
            this.$message.error({message:'品牌名称不能为空'})
            return
          }
          this.$http.post(this.$store.getters.serverIp+'add_brand',data).then((response)=>{
            if(response.data.success){
              this.$message.success({message:response.data.info,duration:1000})
              var obj={}
              obj.label=name
              obj.value=response.data.id
              this.brandList.push(obj)
            }
          })
        }
      }
    }
  }
</script>

<style lang="less">
    .productAddWrap{
      .addBrand{
    top: 27%;
    color: #3a8ee6;
    font-size: 12px;
            &:hover{
              cursor:pointer;      
            }
          }
      .mywidth{
        .el-input__inner{
          width: 52%;
        }
      }
      .logoImg{
            margin-top: 19px;
            max-width:120px;
        }
        .input-group{
            display: inline-block;
            border-collapse: separate;
            position: absolute;
            top: 55%;
            left: 14%;
            .input-group-addon {
                padding: 4px 5px;
                font-size: 14px;
                font-weight: 400;
                line-height: 1;
                color: #555;
                text-align: center;
                background-color: #c0c0c0;
                border-radius: 4px;
                label {
                    display: inline-block;
                    max-width: 100%;
                    margin-bottom: 5px;
                    font-weight: 700;
                    img {
                        vertical-align: middle;
                        cursor: pointer;
                    }
                    input{
                        display: none;
                    }
                }
            }
        }
      .el-tabs.el-tabs--card.el-tabs--top{
          width: 100% !important;
          position:relative;
          display: inline-block !important;
      }
      .el-form{
        width: 78%;
        margin: 0 auto;
        margin-top: 25px;
      }
       .onSubmit{
          position: relative;
          
            .el-form-item--small{
                border-top: 1px solid #ccc !important;
                text-align: center !important;
                width: 100% !important;
                margin-top: 60px !important;
            }
            .el-form-item__content{
                margin: 0 !important;
            }
            .el-button--primary{
                margin-top: 10px !important;
            }
        }
    }
    .title{
        font-size: 24px;
        font-weight: normal;
        border-bottom: 1px solid #ccc;
        color: #324157;
        text-indent: 17px;
        padding: 9px;
    }
    .content{
        padding:5px;
        >button{
            position: absolute;
            top: 60px;
            right: 34px;
            background: #717fa9;
            color: #fff;
            border: 1px solid #393737;
            border-radius: 5px;
            padding: 4px;
        }
        >button:hover{
            cursor:pointer;
            outline:none
        }
        .pageination{
            text-align: center;
            margin: 23px;
        }
    }
   
</style>

